package com.promise.jokerdream.ui.test

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.response.pc.*
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.viewmodel.SettingsViewModel
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch

/**
 * 属性查询测试页面
 * 查询并展示隐藏资料、奥义、专精、神装、神魔阵法等信息
 */
@Composable
fun XmlParseTestPage(
    onBack: () -> Unit,
    viewModel: SettingsViewModel = viewModel()
) {
    var isLoading by remember { mutableStateOf(false) }
    var parsedContent by remember { mutableStateOf("") }
    var errorMessage by remember { mutableStateOf("") }
    var puinInput by remember { mutableStateOf("") }
    
    // 获取用户账户信息
    val account by viewModel.account.collectAsState()
    
    // API实例
    val gameApi = remember { GameApi.getInstance() }
    val coroutineScope = rememberCoroutineScope()

    // 处理返回手势
    BackHandler {
        onBack()
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "属性查询测试",
            onBackClick = onBack
        )

        // 内容区域
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp)
        ) {
            // 说明文本
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primaryContainer)
            ) {
                Text(
                    text = "属性查询测试页面\n\n" +
                            "• 输入用户ID（puin）查询隐藏资料\n" +
                            "• 自动查询所有专精类型（0、1、2、3）\n" +
                            "• 查询奥义、神装、神魔阵法等信息\n" +
                            "• 当前用户：${account?.username ?: "未登录"}\n" +
                            "• 用户ID：${account?.userId ?: "无"}",
                    modifier = Modifier.padding(16.dp),
                    style = MaterialTheme.typography.bodyMedium
                )
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 用户ID输入框
            OutlinedTextField(
                value = puinInput,
                onValueChange = { puinInput = it },
                label = { Text("用户ID (puin)") },
                placeholder = { Text("请输入用户ID...") },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading,
                singleLine = true
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 按钮组
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 查询按钮
                Button(
                    onClick = {
                        if (puinInput.isNotEmpty()) {
                            coroutineScope.launch {
                                queryAllInfo(
                                    gameApi = gameApi,
                                    puin = puinInput,
                                    onLoadingChange = { isLoading = it },
                                    onErrorMessageChange = { errorMessage = it },
                                    onParsedContentChange = { parsedContent = it }
                                )
                            }
                        } else {
                            errorMessage = "请输入用户ID"
                        }
                    },
                    enabled = !isLoading && puinInput.isNotEmpty(),
                    modifier = Modifier.weight(1f)
                ) {
                    Text("查询", fontSize = 12.sp)
                }
                
                // 清空按钮
                OutlinedButton(
                    onClick = {
                        puinInput = ""
                        parsedContent = ""
                        errorMessage = ""
                    },
                    enabled = !isLoading,
                    modifier = Modifier.weight(1f)
                ) {
                    Text("清空", fontSize = 12.sp)
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 加载指示器
            if (isLoading) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        horizontalArrangement = Arrangement.Center,
                        verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("正在查询...")
                    }
                }
            }

            Spacer(modifier = Modifier.height(16.dp))

            // 错误信息显示
            if (errorMessage.isNotEmpty()) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.errorContainer)
                ) {
                    Text(
                        text = errorMessage,
                        modifier = Modifier.padding(16.dp),
                        color = MaterialTheme.colorScheme.onErrorContainer
                    )
                }
                Spacer(modifier = Modifier.height(16.dp))
            }

            // 显示解析结果
            if (parsedContent.isNotEmpty()) {
                Card(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "查询结果:",
                            style = MaterialTheme.typography.titleMedium
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        SelectionContainer {
                            val annotatedText = buildAnnotatedString {
                                // 使用正则表达式匹配 **文本** 格式
                                val regex = Regex("\\*\\*(.*?)\\*\\*")
                                var lastIndex = 0
                                
                                regex.findAll(parsedContent).forEach { matchResult ->
                                    // 添加匹配前的普通文本
                                    if (matchResult.range.first > lastIndex) {
                                        append(parsedContent.substring(lastIndex, matchResult.range.first))
                                    }
                                    
                                    // 添加粗体文本（去掉**标记）
                                    withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
                                        append(matchResult.groupValues[1])
                                    }
                                    
                                    lastIndex = matchResult.range.last + 1
                                }
                                
                                // 添加剩余的普通文本
                                if (lastIndex < parsedContent.length) {
                                    append(parsedContent.substring(lastIndex))
                                }
                            }
                            Text(
                                text = annotatedText,
                                fontFamily = FontFamily.Monospace,
                                fontSize = 11.sp,
                                lineHeight = 14.sp
                            )
                        }
                    }
                }
            }
        }
    }
}

/**
 * 查询所有信息并格式化展示
 */
private suspend fun queryAllInfo(
    gameApi: GameApi,
    puin: String,
    onLoadingChange: (Boolean) -> Unit,
    onErrorMessageChange: (String) -> Unit,
    onParsedContentChange: (String) -> Unit
) {
    onLoadingChange(true)
    onErrorMessageChange("")
    onParsedContentChange("")
    
    try {
        val content = StringBuilder()
        
        // 辅助函数：追加内容并立即更新显示
        fun appendAndUpdate(text: String) {
            content.append(text)
            onParsedContentChange(content.toString())
        }
        
        fun appendLineAndUpdate(text: String = "") {
            content.append(text).append("\n")
            onParsedContentChange(content.toString())
        }
        
        // 并行启动所有查询
        coroutineScope {
            val hideInfoDeferred = async { gameApi.queryHideInfo(puin) }
            val skillEnhanceDeferred = async { gameApi.querySkillEnhance() }
            val weaponSpecializeDeferreds = (0..3).map { typeId ->
                async { gameApi.queryWeaponSpecialize(typeId) }
            }
            val outfitDeferred = async { gameApi.queryOutfit() }
            val ancientGodDeferred = async { gameApi.queryAncientGodFormation() }
            
            // 1. 查询隐藏资料（按顺序等待并展示）
            val hideInfoResult = hideInfoDeferred.await()
            hideInfoResult.fold(
                onSuccess = { response ->
                    if (response.result != 0) {
                        appendLineAndUpdate("查询失败: ${response.msg}")
                    } else {
                        appendLineAndUpdate("====== 企鹅信息 ======")
                        appendLineAndUpdate("昵称: ${response.nickname}(${puin})")
                        appendLineAndUpdate("等级: ${response.level}")
                        appendLineAndUpdate("战力: ${response.realCombat()}")
                        appendLineAndUpdate("生命: ${response.parseHpAdd()}")
                        
                        // 基础属性
                        if (response.baseattr.isNotEmpty()) {
                            response.baseattr
                                .filter { it.name != "生命" }
                                .forEach { attr ->
                                    appendLineAndUpdate("${attr.name}: ${attr.processedValue()}")
                                }
                        }
                        
                        // 门派属性
                        if (response.menpai.isNotEmpty()) {
                            val firstAttr = response.menpai.first()
                            appendLineAndUpdate("门派: ${firstAttr.value}")
                        }
                        appendLineAndUpdate("竞技分段: ${response.arenaRank}")
                        
                        // 武器攻击 vs 武器防御（相反组合）
                        val maxWeaponGroups = maxOf(response.weaponatk.size, response.weaponDfs.size)
                        if (maxWeaponGroups > 0) {
                            appendLineAndUpdate()
                            appendLineAndUpdate("====== 武器属性 ======")
                            for (i in 0 until maxWeaponGroups) {
                                val atkGroup = response.weaponatk.getOrNull(i)
                                val dfsGroup = response.weaponDfs.getOrNull(i)
                                
                                if (atkGroup != null || dfsGroup != null) {
                                    // 命中率 / 闪避率
                                    val hitList = atkGroup?.weaponHit ?: emptyList()
                                    val missList = dfsGroup?.weaponMiss ?: emptyList()
                                    if (hitList.isNotEmpty() || missList.isNotEmpty()) {
                                        appendLineAndUpdate("**命中率/闪避率**")
                                        val maxSize = maxOf(hitList.size, missList.size)
                                        for (j in 0 until maxSize) {
                                            val hitItem = hitList.getOrNull(j)
                                            val missItem = missList.getOrNull(j)
                                            val hitText = hitItem?.value ?: ""
                                            val missText = missItem?.value ?: ""
                                            if (hitText.isNotEmpty() || missText.isNotEmpty()) {
                                                val name = hitItem?.name ?: missItem?.name ?: ""
                                                appendLineAndUpdate("$name:$hitText/$missText")
                                            }
                                        }
                                    }
                                    
                                    // 暴击率 / 抗暴击率
                                    val critList = atkGroup?.weaponCrit ?: emptyList()
                                    val decCritList = dfsGroup?.decWeaponCrit ?: emptyList()
                                    if (critList.isNotEmpty() || decCritList.isNotEmpty()) {
                                        appendLineAndUpdate("**暴击率/抗暴击率**")
                                        val maxSize = maxOf(critList.size, decCritList.size)
                                        for (j in 0 until maxSize) {
                                            val critItem = critList.getOrNull(j)
                                            val decCritItem = decCritList.getOrNull(j)
                                            val critText = critItem?.value ?: ""
                                            val decCritText = decCritItem?.value ?: ""
                                            if (critText.isNotEmpty() || decCritText.isNotEmpty()) {
                                                val name = critItem?.name ?: decCritItem?.name ?: ""
                                                appendLineAndUpdate("$name:$critText/$decCritText")
                                            }
                                        }
                                    }
                                    
                                    // 暴击伤害 / 抗暴击伤害
                                    val critDamageList = atkGroup?.critDamage ?: emptyList()
                                    val decCritDamageList = dfsGroup?.decCritDamage ?: emptyList()
                                    if (critDamageList.isNotEmpty() || decCritDamageList.isNotEmpty()) {
                                        appendLineAndUpdate("**暴击伤害/抗暴击伤害**")
                                        val maxSize = maxOf(critDamageList.size, decCritDamageList.size)
                                        for (j in 0 until maxSize) {
                                            val critDamageItem = critDamageList.getOrNull(j)
                                            val decCritDamageItem = decCritDamageList.getOrNull(j)
                                            val critDamageText = critDamageItem?.value ?: ""
                                            val decCritDamageText = decCritDamageItem?.value ?: ""
                                            if (critDamageText.isNotEmpty() || decCritDamageText.isNotEmpty()) {
                                                val name = critDamageItem?.name ?: decCritDamageItem?.name ?: ""
                                                appendLineAndUpdate("$name:$critDamageText/$decCritDamageText")
                                            }
                                        }
                                    }
                                    
                                    // 伤害值/百分比 / 抗伤害值/百分比
                                    val damageList = atkGroup?.weaponDamage ?: emptyList()
                                    val decDamageList = dfsGroup?.decWeaponDamage ?: emptyList()
                                    if (damageList.isNotEmpty() || decDamageList.isNotEmpty()) {
                                        appendLineAndUpdate("**伤害值/百分比/抗伤害值/百分比**")
                                        val maxSize = maxOf(damageList.size, decDamageList.size)
                                        for (j in 0 until maxSize) {
                                            val damageItem = damageList.getOrNull(j)
                                            val decDamageItem = decDamageList.getOrNull(j)
                                            val damageText = damageItem?.value ?: ""
                                            val decDamageText = decDamageItem?.value ?: ""
                                            if (damageText.isNotEmpty() || decDamageText.isNotEmpty()) {
                                                val name = damageItem?.name ?: decDamageItem?.name ?: ""
                                                appendLineAndUpdate("$name:$damageText/$decDamageText")
                                            }
                                        }
                                    }
                                    
                                    // 穿透 / 抗穿透
                                    val penetrateList = atkGroup?.weaponPenetrate ?: emptyList()
                                    val decPenetrateList = dfsGroup?.decWeaponPenetrate ?: emptyList()
                                    if (penetrateList.isNotEmpty() || decPenetrateList.isNotEmpty()) {
                                        appendLineAndUpdate("**穿透/抗穿透**")
                                        val maxSize = maxOf(penetrateList.size, decPenetrateList.size)
                                        for (j in 0 until maxSize) {
                                            val penetrateItem = penetrateList.getOrNull(j)
                                            val decPenetrateItem = decPenetrateList.getOrNull(j)
                                            val penetrateText = penetrateItem?.value ?: ""
                                            val decPenetrateText = decPenetrateItem?.value ?: ""
                                            if (penetrateText.isNotEmpty() || decPenetrateText.isNotEmpty()) {
                                                val name = penetrateItem?.name ?: decPenetrateItem?.name ?: ""
                                                appendLineAndUpdate("$name:$penetrateText/$decPenetrateText")
                                            }
                                        }
                                    }
                                    
                                    // 抗韧性 / 韧性
                                    val decToughnessList = atkGroup?.decWeaponToughness ?: emptyList()
                                    val toughnessList = dfsGroup?.weaponToughness ?: emptyList()
                                    if (decToughnessList.isNotEmpty() || toughnessList.isNotEmpty()) {
                                        appendLineAndUpdate("**抗韧性/韧性**")
                                        val maxSize = maxOf(decToughnessList.size, toughnessList.size)
                                        for (j in 0 until maxSize) {
                                            val decToughnessItem = decToughnessList.getOrNull(j)
                                            val toughnessItem = toughnessList.getOrNull(j)
                                            val decToughnessText = decToughnessItem?.value ?: ""
                                            val toughnessText = toughnessItem?.value ?: ""
                                            if (decToughnessText.isNotEmpty() || toughnessText.isNotEmpty()) {
                                                val name = decToughnessItem?.name ?: toughnessItem?.name ?: ""
                                                appendLineAndUpdate("$name:$decToughnessText/$toughnessText")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        
                        // 技能/空手攻击 vs 技能/空手防御（相反组合）
                        val maxSuGroups = maxOf(response.suatk.size, response.sudef.size)
                        if (maxSuGroups > 0) {
                            appendLineAndUpdate()
                            appendLineAndUpdate("====== 技能/空手属性 ======")
                            for (i in 0 until maxSuGroups) {
                                val atkGroup = response.suatk.getOrNull(i)
                                val defGroup = response.sudef.getOrNull(i)
                                
                                if (atkGroup != null || defGroup != null) {
                                    // 命中率 / 闪避率
                                    val hitList = atkGroup?.suhit ?: emptyList()
                                    val missList = defGroup?.sumiss ?: emptyList()
                                    if (hitList.isNotEmpty() || missList.isNotEmpty()) {
                                        appendLineAndUpdate("**命中率/闪避率**")
                                        val maxSize = maxOf(hitList.size, missList.size)
                                        for (j in 0 until maxSize) {
                                            val hitItem = hitList.getOrNull(j)
                                            val missItem = missList.getOrNull(j)
                                            val hitText = hitItem?.value ?: ""
                                            val missText = missItem?.value ?: ""
                                            if (hitText.isNotEmpty() || missText.isNotEmpty()) {
                                                val name = hitItem?.name ?: missItem?.name ?: ""
                                                appendLineAndUpdate("$name:$hitText/$missText")
                                            }
                                        }
                                    }
                                    
                                    // 暴击率 / 抗暴击率
                                    val critRateList = atkGroup?.sucritrate ?: emptyList()
                                    val decCritRateList = defGroup?.dsucritrate ?: emptyList()
                                    if (critRateList.isNotEmpty() || decCritRateList.isNotEmpty()) {
                                        appendLineAndUpdate("**暴击率/抗暴击率**")
                                        val maxSize = maxOf(critRateList.size, decCritRateList.size)
                                        for (j in 0 until maxSize) {
                                            val critRateItem = critRateList.getOrNull(j)
                                            val decCritRateItem = decCritRateList.getOrNull(j)
                                            val critRateText = critRateItem?.value ?: ""
                                            val decCritRateText = decCritRateItem?.value ?: ""
                                            if (critRateText.isNotEmpty() || decCritRateText.isNotEmpty()) {
                                                val name = critRateItem?.name ?: decCritRateItem?.name ?: ""
                                                appendLineAndUpdate("$name:$critRateText/$decCritRateText")
                                            }
                                        }
                                    }
                                    
                                    // 暴击伤害 / 抗暴击伤害
                                    val critList = atkGroup?.sucrit ?: emptyList()
                                    val decCritList = defGroup?.dsucrit ?: emptyList()
                                    if (critList.isNotEmpty() || decCritList.isNotEmpty()) {
                                        appendLineAndUpdate("**暴击伤害/抗暴击伤害**")
                                        val maxSize = maxOf(critList.size, decCritList.size)
                                        for (j in 0 until maxSize) {
                                            val critItem = critList.getOrNull(j)
                                            val decCritItem = decCritList.getOrNull(j)
                                            val critText = critItem?.value ?: ""
                                            val decCritText = decCritItem?.value ?: ""
                                            if (critText.isNotEmpty() || decCritText.isNotEmpty()) {
                                                val name = critItem?.name ?: decCritItem?.name ?: ""
                                                appendLineAndUpdate("$name:$critText/$decCritText")
                                            }
                                        }
                                    }
                                    
                                    // 伤害 / 抗伤害
                                    val damageList = atkGroup?.sudamage ?: emptyList()
                                    val decDamageList = defGroup?.dsudamage ?: emptyList()
                                    if (damageList.isNotEmpty() || decDamageList.isNotEmpty()) {
                                        appendLineAndUpdate("**伤害/抗伤害**")
                                        val maxSize = maxOf(damageList.size, decDamageList.size)
                                        for (j in 0 until maxSize) {
                                            val damageItem = damageList.getOrNull(j)
                                            val decDamageItem = decDamageList.getOrNull(j)
                                            val damageText = damageItem?.value ?: ""
                                            val decDamageText = decDamageItem?.value ?: ""
                                            if (damageText.isNotEmpty() || decDamageText.isNotEmpty()) {
                                                val name = damageItem?.name ?: decDamageItem?.name ?: ""
                                                appendLineAndUpdate("$name:$damageText/$decDamageText")
                                            }
                                        }
                                    }
                                    
                                    // 穿透 / 抗穿透
                                    val penetrateList = atkGroup?.supenettration ?: emptyList()
                                    val decPenetrateList = defGroup?.decSupenettration ?: emptyList()
                                    if (penetrateList.isNotEmpty() || decPenetrateList.isNotEmpty()) {
                                        appendLineAndUpdate("**穿透/抗穿透**")
                                        val maxSize = maxOf(penetrateList.size, decPenetrateList.size)
                                        for (j in 0 until maxSize) {
                                            val penetrateItem = penetrateList.getOrNull(j)
                                            val decPenetrateItem = decPenetrateList.getOrNull(j)
                                            val penetrateText = penetrateItem?.value ?: ""
                                            val decPenetrateText = decPenetrateItem?.value ?: ""
                                            if (penetrateText.isNotEmpty() || decPenetrateText.isNotEmpty()) {
                                                val name = penetrateItem?.name ?: decPenetrateItem?.name ?: ""
                                                appendLineAndUpdate("$name:$penetrateText/$decPenetrateText")
                                            }
                                        }
                                    }
                                    
                                    // 抗韧性 / 韧性
                                    val decToughnessList = atkGroup?.decSutoughness ?: emptyList()
                                    val toughnessList = defGroup?.sutoughness ?: emptyList()
                                    if (decToughnessList.isNotEmpty() || toughnessList.isNotEmpty()) {
                                        appendLineAndUpdate("**抗韧性/韧性**")
                                        val maxSize = maxOf(decToughnessList.size, toughnessList.size)
                                        for (j in 0 until maxSize) {
                                            val decToughnessItem = decToughnessList.getOrNull(j)
                                            val toughnessItem = toughnessList.getOrNull(j)
                                            val decToughnessText = decToughnessItem?.value ?: ""
                                            val toughnessText = toughnessItem?.value ?: ""
                                            if (decToughnessText.isNotEmpty() || toughnessText.isNotEmpty()) {
                                                val name = decToughnessItem?.name ?: toughnessItem?.name ?: ""
                                                appendLineAndUpdate("$name:$decToughnessText/$toughnessText")
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                onFailure = { error ->
                    appendLineAndUpdate("查询失败: ${error.message}")
                }
            )
            
            appendLineAndUpdate()
            
            // 2. 查询奥义（等待已启动的查询）
            appendLineAndUpdate("====== 奥义 ======")
            val skillEnhanceResult = skillEnhanceDeferred.await()
            skillEnhanceResult.fold(
                onSuccess = { response ->
                    if (response.result != 0) {
                        appendLineAndUpdate("查询失败: ${response.msg}")
                    } else {
                        val skillInfo = response.storage
                            .filter { it.storageLevel.isNotEmpty() }
                            .map { "(${it.skillName} ${it.storageLevel})" }
                        val convertedLevel = response.convertLevel()
                        appendLineAndUpdate("奥义：$convertedLevel ${skillInfo.joinToString("")}")
                    }
                },
                onFailure = { error ->
                    appendLineAndUpdate("查询失败: ${error.message}")
                }
            )
            
            appendLineAndUpdate()
            
            // 3. 查询所有专精类型（0、1、2、3）（等待已启动的查询）
            appendLineAndUpdate("====== 专精 ======")
            weaponSpecializeDeferreds.forEachIndexed { typeId, deferred ->
                val weaponSpecializeResult = deferred.await()
                weaponSpecializeResult.fold(
                    onSuccess = { response ->
                        if (response.result != 0) {
                            val typeName = response.getWeaponTypeName()
                            appendLineAndUpdate("$typeName 查询失败: ${response.msg}")
                        } else {
                            val typeName = response.getWeaponTypeName()
                            val formattedLevel = response.getFormattedLevel()
                            val storageInfo = response.storages.map { "(${it.weaponName} ${it.storageLevel})" }
                            val storageText = if (storageInfo.isNotEmpty()) {
                                " ${storageInfo.joinToString("")}"
                            } else {
                                ""
                            }
                            appendLineAndUpdate("$typeName: $formattedLevel$storageText")
                        }
                    },
                    onFailure = { error ->
                        appendLineAndUpdate("类型$typeId 查询失败: ${error.message}")
                    }
                )
            }
            
            appendLineAndUpdate()
            
            // 4. 查询神装（等待已启动的查询）
            appendLineAndUpdate("====== 神装 ======")
            val outfitResult = outfitDeferred.await()
            outfitResult.fold(
                onSuccess = { response ->
                    if (response.result != 0) {
                        appendLineAndUpdate("查询失败: ${response.msg}")
                    } else {
                        response.magicOutfits
                            .filterIndexed { index, _ -> index % 2 == 0 }
                            .forEach { outfit ->
                                val skillInfo = outfit.skills.map { skill ->
                                    val suitLevelText = if (skill.suitLevel.isNotEmpty()) "+${skill.suitLevel}" else ""
                                    "(${skill.skillName}${skill.skillLevel} $suitLevelText)"
                                }
                                val skillText = if (skillInfo.isNotEmpty()) {
                                    " ${skillInfo.joinToString("")}"
                                } else {
                                    ""
                                }
                                appendLineAndUpdate("${outfit.magicOutfitName}：${outfit.level}$skillText")
                            }
                    }
                },
                onFailure = { error ->
                    appendLineAndUpdate("查询失败: ${error.message}")
                }
            )
            
            appendLineAndUpdate()
            
            // 5. 查询神魔阵法（等待已启动的查询）
            appendLineAndUpdate("====== 神魔 ======")
            val ancientGodResult = ancientGodDeferred.await()
            ancientGodResult.fold(
                onSuccess = { response ->
                    if (response.result != 0) {
                        appendLineAndUpdate("查询失败: ${response.msg}")
                    } else {
                        // 神魔鼎
                        if (response.treasureInfo.isNotEmpty()) {
                            val treasureInfo = response.treasureInfo.map { "(${it.name} ${it.level})" }
                            appendLineAndUpdate("神魔鼎：${treasureInfo.joinToString("")}")
                        }
                        
                        // 神魔阵法
                        if (response.arraySkillInfo.isNotEmpty()) {
                            val skillNames = response.arraySkillInfo.map { "(${it.skillName})" }
                            appendLineAndUpdate("神魔阵法：${skillNames.joinToString("")}")
                        }
                    }
                },
                onFailure = { error ->
                    appendLineAndUpdate("查询失败: ${error.message}")
                }
            )
        }
        
    } catch (e: Exception) {
        onErrorMessageChange("查询异常: ${e.message}")
    } finally {
        onLoadingChange(false)
    }
}
